package com.umbacos.udm.client.presenter.popup;

import java.util.Collection;
import java.util.Iterator;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.umbacos.udm.client.model.UdmStatus;
import com.umbacos.udm.client.view.UploadPopupView;

public class UploadPopupPresenter {

	final private UploadPopupView uploadPopup;
	final private UdmStatus udmStatus;
	
	public UploadPopupPresenter(UdmStatus udmStatus){
		this.udmStatus=udmStatus;
		this.uploadPopup=new UploadPopupView();
	}
	
	public void bind(){
		uploadPopup.btSubmit.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				uploadPopup.form.submit();				
			}
		});

		uploadPopup.btCancel.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				uploadPopup.hide();
			}
		});

		uploadPopup.form.addSubmitHandler(new SubmitHandler() {
			
			@Override
			public void onSubmit(SubmitEvent event) {
				if (uploadPopup.upload.getFilename().length() == 0) {
					Window.alert("The text box must not be empty");
					event.cancel();
				} else {
					uploadPopup.hourglass.center();
				}
			}
		});
		
		uploadPopup.form.addSubmitCompleteHandler(new SubmitCompleteHandler() {
			
			@Override
			public void onSubmitComplete(SubmitCompleteEvent event) {
				uploadPopup.hourglass.hide();
				uploadPopup.hide();
				udmStatus.update(UdmStatus.UPDATE_FILES);

				Collection<String> cks=Cookies.getCookieNames();
				for (Iterator<String> i=cks.iterator();i.hasNext();) {
					String ck=i.next();
					Window.alert(ck +"="+Cookies.getCookie(ck));
				}
			}
		});

		uploadPopup.center();
	}

}
